<template>
    <form class="validate-form-container">
        <slot name="default"></slot>
        <div class="submit-area" @click.prevent="submitForm">
            <slot name="submit">
                <button type="submit" class="btn btn-primary">提交</button>
            </slot>
        </div>
    </form>
</template>
<script lang="ts">
import { defineComponent,onUnmounted } from 'vue'
import mitt from 'mitt'
// 事件监听器--父组件监听子组件-mitt插件
export const emitter = mitt()
type vaildateFunc = ()=>boolean
export default defineComponent({
    emits:['form-submit'],
    setup(props,context){
        let funcArr:vaildateFunc[] = []
        const submitForm = ()=>{
            const result = funcArr.map(func =>func()).every(result=>result)
            context.emit('form-submit',true)
        }
        // 回调函数
        const callbalk = (func:vaildateFunc)=>{
            funcArr.push(func)
        }
        // 添加到监听器中
        emitter.on('form-item-created',callbalk)
        // 组件卸载时，清理监听器
        onUnmounted(()=>{
            emitter.off('form-item-created',callbalk)
            funcArr = []
        })
        return {
            submitForm
        }
    }
})
</script>
